﻿using System;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Security;
using ASPNETVN.PORTAL.Components.Helpers;
using ASPNETVN.PORTAL.Components.Security;
using ASPNETVN.PORTAL.Components.UI;

namespace ASPNETVN.PORTAL.Controls
{
    public partial class SignIn : AloneControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void btnPasswordRecovery_Click(object sender, EventArgs e)
        {
            if (User.CheckExist(txtRecoveryEmail.Text))
            {
                string newPassword = User.ResetPassword(txtRecoveryEmail.Text);
                if (newPassword.Length > 0)
                {
                    StringBuilder body = new StringBuilder();
                    body.Append("Xin chao!<br><br>");
                    body.AppendFormat("Ban da dang ky nhan lai mat khau moi cua Web Site <a href='http://www.asp.net.vn'><strong>ASP.NET VIET NAM</strong></a>.<br><br>");
                    body.AppendFormat("Thong tin dang nhap Web Site ASP.NET VIETNAM cua ban nhu sau: <br><br>- Email dang nhap: {0}<br>- Mat khau moi: {1}<br><br>", txtRecoveryEmail.Text, newPassword);
                    body.Append("<br>Chuc ban vui ve!");
                    body.Append("<br><br><hr>");
                    body.Append("<br><strong>ASP.NET VIET NAM - Chia se kinh nghiem, nang cao ky nang.</strong>");
                    body.Append("<br>Web Master: Ngo Thanh Tung");
                    body.Append("<br>Mobile: 0905157803");

                    MailHelper.SendMail("webmater@asp.net.vn", txtRecoveryEmail.Text, "", "ngothanhtung.it@gmail.com", "ASP.NET VIETNAM - Mat khau moi", body.ToString(), MailPriority.High);
                    txtMessage.Text = "Mật khẩu mới đã được gửi đến email bạn vừa cung cấp.";
                    txtRecoveryEmail.Text = string.Empty;
                }
            }
            else
            {
                txtMessage.Text = "Không thể khôi phục lại mật khẩu.<br/>Lý do: Email này không tồn tại.<br/>Vui lòng kiểm tra lại!";
            }
        }

        protected void btnSignIn_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                // Attempt to Validate User Credentials using User
                IdentityUser identityUser = User.Login(txtEmail.Text, txtPassword.Text);
                if (identityUser != null)
                {

                    // Create the cookie that contains the forms authentication ticket.
                    HttpCookie authCookie = FormsAuthentication.GetAuthCookie(identityUser.ToString(), chkRemember.Checked);
                    
                    // Get the FormsAuthenticationTicket out of the encrypted cookie.
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

                    // Create a new FormsAuthenticationTicket that includes our custom User Data.
                    // Get roles from UserRoles table, and add to cookie
                    string[] roles = User.GetRoles(identityUser.ID);

                    // Create a string to persist the roles.
                    string rolesString = string.Empty;
                    foreach (string role in roles)
                    {
                        rolesString += role;
                        rolesString += ";";
                    }

                    FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, rolesString);
                    
                    // Update the authCookie's Value to use the encrypted version of newTicket.
                    authCookie.Value = FormsAuthentication.Encrypt(newTicket);

                    // Manually add the authCookie to the Cookies collection.
                    Response.Cookies.Add(authCookie);

                    // Determine redirect URL and send user there.
                    //string redirectUrl = FormsAuthentication.GetRedirectUrl(txtEmail.Text, chkRemember.Checked);
                    //Response.Redirect(redirectUrl);

                    // Use security system to set the UserID within a client-side Cookie
                    //FormsAuthentication.SetAuthCookie(identityUser.ToString(), chkRemember.Checked);

                    // Redirect browser back to recent page.
                    if (Request.QueryString["returnUrl"] != null)
                    {
                        int pos = Request.RawUrl.ToLower().IndexOf("returnurl");
                        string returnUrl = Request.RawUrl.Substring(pos + 10);
                        Response.Redirect(Server.UrlDecode(returnUrl));
                    }
                    else
                    {
                        Response.Redirect("~/Default.aspx");
                    }
                }
                else
                {
                    txtMessage.Text = "Đăng nhập không thành công!";
                }
            }
        }

        protected void btnRegister_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Register.aspx");
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            // Redirect browser back to recent page.
            if (Request.QueryString["returnUrl"] != null)
            {
                int pos = Request.RawUrl.ToLower().IndexOf("returnurl");
                string returnUrl = Request.RawUrl.Substring(pos + 10);
                Response.Redirect(Server.UrlDecode(returnUrl));
            }
            else
            {
                Response.Redirect("~/Default.aspx");
            }
        }
    }
}